import os
import json
import uuid
from pathlib import Path
from typing import Optional, Dict, Any, List, Union
from app.models.metadata import Subject, Col, Row, Metadata
from datetime import datetime


class MetadataEncoder(json.JSONEncoder):
    """自定义JSON编码器，处理特殊类型的序列化"""

    def default(self, obj):
        if isinstance(obj, Subject):
            return obj.value
        if isinstance(obj, (Col, Row)):
            return obj.to_dict()
        if isinstance(obj, Metadata):
            return obj.to_dict()
        return super().default(obj)


def get_data_dir() -> Path:
    """获取数据存储根目录"""
    data_dir = Path(__file__).parent.parent / 'data'
    data_dir.mkdir(exist_ok=True)
    return data_dir


def get_user_dir(user_id: str) -> Path:
    """获取用户数据目录"""
    user_dir = get_data_dir() / user_id
    user_dir.mkdir(exist_ok=True)
    return user_dir


def get_upload_dir() -> Path:
    """获取上传文件目录"""
    upload_dir = get_data_dir() / 'uploads'
    upload_dir.mkdir(exist_ok=True)
    return upload_dir


def generate_user_id() -> str:
    """生成新的用户ID"""
    return str(uuid.uuid4())
